import React, { useState, useReducer, useEffect, useMemo } from "react";
import { withRouter } from "react-router-dom";

import {
  NavBar,
  Icon,
  SearchBar,
  PullToRefresh,
  Result,
  Toast,
} from "antd-mobile";
import { reqHouses, reqHousesCondition, reqCommunityData } from "../../api";
import Selector from "./components/Selector";
import HouseList from "../../components/HouseList";
import { chooseCityKey } from "../../utils";
import "./index.scss";

export default withRouter(function Find(props) {
  const { history, location } = props;
  const { state } = location;
  const chooseCity = JSON.parse(localStorage.getItem(chooseCityKey)); //选择的城市数据

  const [searchText, setSearchText] = useState(""); //输入框value
  // const [communityData, setCommunityData] = useState([])  //查询到的小区数据

  const [condition, setCondition] = useState(null); //房屋查询条件
  const [data, setData] = useState({ list: [], count: 0 }); //房屋数据
  const [isEmpty, setIsEmpty] = useState(false); //数据是否为空
  const [nextRange, setNextRange] = useState({
    start: 1,
    end: 20,
    isGetting: true,
    isRequest: false,
  }); //下一个数据的获取范围

  const [selectors, dispatch] = useReducer(
    (state, action) => {
      //筛选模块的初始化和状态管理
      let res = [...state];
      switch (action.type) {
        case "open": //打开
          res.find((i) => i.id === action.id).status = true;
          return [...res];
        case "close": //关闭
          if (action.id) {
            //关闭指定ID
            res.find((i) => i.id === action.id).status = false;
          } else {
            //关闭已open的
            if (res.find((i) => i.status === true))
              res.find((i) => i.status === true).status = false;
          }
          return [...res];
        case "update": //更新
          res.find((i) => i.id === action.id).data = action.data;
          res.find((i) => i.id === action.id).status = false;
          setData({ list: [], count: 0 });
          setIsEmpty(false);
          setNextRange({
            start: 1,
            end: 20,
            isGetting: true,
            isRequest: false,
          });
          return [...res];
        case "clear": //清除筛选
          let target = res[3];
          target.status = false;
          target.data = {
            roomType: [],
            oriented: [],
            floor: [],
            characteristic: [],
          };
          setData({ list: [], count: 0 });
          setIsEmpty(false);
          setNextRange({
            start: 1,
            end: 20,
            isGetting: true,
            isRequest: false,
          });
          return [...res];
        default:
          return state;
      }
    },
    [
      { id: 1, name: "区域", type: "area", status: false, data: [] },
      {
        id: 2,
        name: "方式",
        type: "mode",
        status: false,
        data: state && state.rentType ? [state.rentType] : [],
      },
      { id: 3, name: "租金", type: "price", status: false, data: [] },
      {
        id: 4,
        name: "筛选",
        type: "filter",
        status: false,
        data: { roomType: [], oriented: [], floor: [], characteristic: [] },
      },
    ]
  );

  const setRange = () => {
    //分页
    console.log("分页");
    const len = data.list.length;
    const count = data.count;
    if (count === 0) {
      Toast.info("没有数据了", 2, null, false);
      return;
    }
    let start = len === count ? len : len + 1;
    let end = len + 20 > count ? count : len + 20;
    if (start === end) {
      Toast.info("没有数据了", 2, null, false);
      return;
    }
    setNextRange({ start, end, isGetting: true, isRequest: false });
  };

  const houseList = useMemo(
    () => <HouseList list={data.list} history={history}></HouseList>,
    [data, history]
  );

  useEffect(() => {
    async function getList(params) {
      //获取房源数据
      setNextRange({ ...nextRange, isRequest: true });
      if (nextRange.isRequest)
        return setNextRange({ ...nextRange, isGetting: false });
      if (isEmpty || (!isEmpty && data.count === nextRange.end)) {
        setNextRange({ ...nextRange, isGetting: false, isRequest: false });
        return Toast.info("没有数据咯", 2, null, false);
      }
      Toast.loading("正在加载数据...", 0);
      let res = await reqHouses(params);
      setData({
        list: [...data.list, ...res.body.list],
        count: res.body.count,
      });
      Toast.hide();
      if (nextRange.start === 1)
        Toast.info("为您找到" + res.body.count + "套房源", 2, null, false);
      if (res.body.count === 0) {
        setIsEmpty(true);
      }
      setNextRange({ ...nextRange, isGetting: false, isRequest: false });
    }
    async function getCondition(params) {
      //获取房屋筛选条件
      let res = await reqHousesCondition(params);
      setCondition(res.body);
    }

    function getParams() {
      //整合获取房源参数
      const keys = [
        "area",
        "rentType",
        "price",
        "roomType",
        "oriented",
        "floor",
        "characteristic",
      ];
      let res = { cityId: chooseCity.id };
      keys.reduce((p, key, index) => {
        if (index < 3) {
          let data = selectors[index].data;
          if (data.length !== 0) {
            if (data.length === 2) {
              if (data[1] !== "null") {
                p[
                  data[1].split("|")[0].toLowerCase() === "area"
                    ? "area"
                    : "subway"
                ] = data[1];
              }
            } else if (data.length === 3) {
              if (data[2] !== "null") {
                p[
                  data[2].split("|")[0].toLowerCase() === "area"
                    ? "area"
                    : "subway"
                ] = data[2];
              } else {
                p[
                  data[1].split("|")[0].toLowerCase() === "area"
                    ? "area"
                    : "subway"
                ] = data[1];
              }
            } else if (data.length === 1) {
              p[key] = data[0];
            }
          }
        } else {
          if (selectors[index]) {
            let arr = Object.values(selectors[index].data).flat(2);
            p.more =
              arr.length === 0
                ? null
                : arr.reduce((_p, c) => {
                    _p = _p + c + ",";
                    return _p;
                  }, "");
          }
        }
        return p;
      }, res);

      //当有选择小区时将地区改为小区的id
      if (state && state.community !== "") {
        res.area = state.community;
      }
      //设置个数获取
      res.start = nextRange.start;
      res.end = nextRange.end;

      return res;
    }

    async function getCommunityData(params) {
      //社区和小区名称查询
      let res = await reqCommunityData(params);
      // setCommunityData(res.body)
      if (res.body.length === 0) setIsEmpty(true);
    }

    if (data.list.length === 0 && !isEmpty && nextRange.isGetting)
      getList(getParams());

    if (!condition) getCondition({ id: chooseCity.id });
    if (searchText !== "") {
      getCommunityData({ name: searchText, id: chooseCity.id });
      setIsEmpty(false);
    }
    if (
      nextRange.isGetting &&
      nextRange.start !== 1 &&
      data.list.length !== nextRange.end
    )
      getList(getParams());
  }, [data, condition, selectors, isEmpty, chooseCity, searchText, nextRange, state]);

  return (
    <div className="find-page">
      <div className="find-navbar">
        <NavBar
          key="find-navbar"
          mode="light"
          icon={<Icon type="left" color="#666" onClick={history.goBack} />}
          rightContent={[
            <i
              key={1}
              className="iconfont icon-map"
              style={{ color: "#21b97a", fontSize: "25px " }}
              onClick={() => history.push("/map")}
            ></i>,
          ]}
        >
          <div className="find-search-wrap" key="find-navbar-children">
            <div
              className="find-to-citylist"
              onClick={() =>
                history.push("/cityList", { cityName: chooseCity.name })
              }
            >
              <span>{chooseCity.name}</span>
              <i key={2} className="iconfont icon-arrow" />
            </div>
            <SearchBar
              className="find-search-input"
              placeholder={
                state && state.community
                  ? state.communityName
                  : "请输入小区或地址"
              }
              onSubmit={(value) => setSearchText(value)}
              onClear={() => setSearchText("")}
              onFocus={() => history.replace("/search", { path: "/home/find" })}
            />
          </div>
        </NavBar>
      </div>
      <div className="find-selectors">
        {useMemo(
          () => (
            <Selector
              selectors={selectors}
              dispatch={dispatch}
              condition={condition}
            ></Selector>
          ),
          [selectors, condition]
        )}
      </div>
      <div
        className={
          "find-list " + (selectors.some((i) => i.status) ? "mask" : "")
        }
      >
        {isEmpty ? (
          <Result title="搜索结果" message="找不到您要的房源" />
        ) : (
          <PullToRefresh
            damping={60}
            direction="up"
            style={{
              height: "calc(100vh - 150px)",
              overflow: "auto",
            }}
            onRefresh={() => setRange()}
          >
            {houseList}
          </PullToRefresh>
        )}
      </div>
    </div>
  );
});
